<template>
  <div class="product-detail-container" v-loading="loading">
    <div v-if="loading" class="loading-placeholder">
      <div class="spinner"></div>
      <p>正在加载商品信息...</p>
    </div>
    
    <div v-else-if="!product" class="error-placeholder">
      <i class="el-icon-warning-outline"></i>
      <p>商品不存在或已下架</p>
      <el-button type="primary" @click="goBack">返回商品列表</el-button>
    </div>
    
    <template v-else>
      <div class="product-detail-content">
        <!-- 左侧商品图片展示 -->
        <div class="product-gallery">
          <div class="main-image">
            <el-image 
              :src="currentImage || product.coverImage || 'https://via.placeholder.com/400'" 
              fit="contain"
              :preview-src-list="allProductImages">
            </el-image>
            
            <div class="product-badges">
              <span v-if="product.isNew" class="badge new">新品</span>
              <span v-if="product.isHot" class="badge hot">热销</span>
              <span v-if="product.isRecommended" class="badge recommend">推荐</span>
            </div>
          </div>
          
          <div class="thumbnail-list" v-if="productImages.length > 0">
            <div 
              v-for="image in productImages" 
              :key="image.id" 
              class="thumbnail" 
              :class="{ active: currentImage === image.imageUrl }"
              @click="setCurrentImage(image.imageUrl)">
              <img :src="image.imageUrl" :alt="product.name">
            </div>
            
            <div 
              v-if="product.coverImage && !hasMainImage" 
              class="thumbnail" 
              :class="{ active: currentImage === product.coverImage }"
              @click="setCurrentImage(product.coverImage)">
              <img :src="product.coverImage" :alt="product.name">
            </div>
          </div>
        </div>
        
        <!-- 右侧商品信息 -->
        <div class="product-info">
          <h1 class="product-title">{{ product.name }}</h1>
          
          <div class="product-meta">
            <div class="meta-item" v-if="product.brand">
              <span class="label">品牌：</span>
              <span class="value">{{ product.brand }}</span>
            </div>
            <div class="meta-item">
              <span class="label">SKU：</span>
              <span class="value">{{ product.sku }}</span>
            </div>
            <div class="meta-item">
              <span class="label">销量：</span>
              <span class="value">{{ product.sales || 0 }}</span>
            </div>
          </div>
          
          <div class="product-price">
            <div class="current-price">¥{{ product.price }}</div>
            <div class="original-price" v-if="product.originalPrice && product.originalPrice > product.price">
              ¥{{ product.originalPrice }}
            </div>
            <div class="discount-tag" v-if="product.originalPrice && product.originalPrice > product.price">
              {{ Math.round((1 - product.price / product.originalPrice) * 100) }}% OFF
            </div>
          </div>
          
          <div class="product-actions">
            <div class="quantity-selector">
              <span class="label">数量：</span>
              <el-input-number 
                v-model="quantity" 
                :min="1"
                :max="product.stock || 999"
                size="small">
              </el-input-number>
              <span class="stock-info" v-if="product.stock">库存：{{ product.stock }}</span>
            </div>
            
            <div class="action-buttons">
              <el-button 
                type="primary" 
                size="large" 
                :disabled="!product.isPublished"
                @click="addToCart">
                <i class="el-icon-shopping-cart-2"></i> 加入购物车
              </el-button>
              
              <el-button 
                type="danger" 
                size="large" 
                :disabled="!product.isPublished"
                @click="buyNow">
                立即购买
              </el-button>
              
              <el-button 
                type="default" 
                icon="el-icon-star-off" 
                size="large"
                @click="addToFavorite">
                收藏
              </el-button>
            </div>
            
            <div class="product-status" v-if="!product.isPublished">
              <el-alert
                title="该商品已下架"
                type="warning"
                :closable="false"
                show-icon>
              </el-alert>
            </div>
          </div>
          
          <div class="product-attributes" v-if="product.attributes && product.attributes.length > 0">
            <div class="attribute-title">商品参数</div>
            <ul class="attribute-list">
              <li v-for="attr in product.attributes" :key="attr.id" class="attribute-item">
                <span class="attribute-name">{{ attr.name }}：</span>
                <span class="attribute-value">{{ attr.value }}</span>
              </li>
            </ul>
          </div>
        </div>
      </div>
      
      <!-- 商品详情区 -->
      <div class="product-description-section">
        <div class="section-tabs">
          <el-tabs v-model="activeTab">
            <el-tab-pane label="商品详情" name="description">
              <div class="product-description" v-if="product.description">
                <div v-html="formattedDescription"></div>
              </div>
              <el-empty v-else description="暂无商品详情" :image-size="200"></el-empty>
            </el-tab-pane>
            <el-tab-pane label="规格参数" name="attributes">
              <div v-if="product.attributes && product.attributes.length > 0" class="attributes-table">
                <el-table :data="product.attributes" stripe border>
                  <el-table-column prop="name" label="参数名称" width="180"></el-table-column>
                  <el-table-column prop="value" label="参数值"></el-table-column>
                </el-table>
              </div>
              <el-empty v-else description="暂无规格参数" :image-size="200"></el-empty>
            </el-tab-pane>
            <el-tab-pane label="用户评价" name="reviews">
              <el-empty description="暂无用户评价" :image-size="200"></el-empty>
            </el-tab-pane>
          </el-tabs>
        </div>
      </div>
      
      <!-- 相关商品推荐 -->
      <div class="related-products-section">
        <h2 class="section-title">相关商品推荐</h2>
        <div class="related-products-list">
          <div class="empty-placeholder" v-if="relatedProducts.length === 0">
            <el-empty description="暂无相关商品" :image-size="200"></el-empty>
          </div>
          <div v-else class="products-slider">
            <div 
              v-for="item in relatedProducts" 
              :key="item.id" 
              class="product-card"
              @click="viewProductDetail(item.id)">
              <div class="product-image">
                <img :src="item.coverImage || 'https://via.placeholder.com/200'" :alt="item.name">
              </div>
              <div class="product-card-info">
                <h3 class="product-card-name">{{ item.name }}</h3>
                <div class="product-card-price">¥{{ item.price }}</div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </template>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import productApi from '../../api/product';
import { createOrder } from '../../api/order';
import { useUserStore } from '../../stores/user'; // 假设有用户store

// 路由相关
const route = useRoute();
const router = useRouter();

// 商品数据
const loading = ref(true);
const product = ref(null);
const productImages = ref([]);
const relatedProducts = ref([]);
const currentImage = ref('');
const quantity = ref(1);
const activeTab = ref('description');

// 计算属性
const hasMainImage = computed(() => {
  return productImages.value.some(img => img.main);
});

const allProductImages = computed(() => {
  const images = productImages.value.map(img => img.imageUrl);
  if (product.value?.coverImage && !images.includes(product.value.coverImage)) {
    images.unshift(product.value.coverImage);
  }
  return images;
});

const formattedDescription = computed(() => {
  if (!product.value?.description) return '';
  // 将普通文本中的换行符转换为HTML换行
  return product.value.description.replace(/\n/g, '<br>');
});

// 方法
const fetchProductDetail = async (productId) => {
  loading.value = true;
  try {
    const result = await productApi.getProductById(productId);
    product.value = result.data;
    
    // 获取商品图片
    await fetchProductImages(productId);
    
    // 获取相关商品
    await fetchRelatedProducts(productId);
    
    // 设置默认显示图片
    if (hasMainImage.value) {
      const mainImage = productImages.value.find(img => img.main);
      if (mainImage) {
        currentImage.value = mainImage.imageUrl;
      }
    } else if (product.value.coverImage) {
      currentImage.value = product.value.coverImage;
    }
  } catch (error) {
    console.error('获取商品详情失败:', error);
    ElMessage.error('获取商品详情失败');
    product.value = null;
  } finally {
    loading.value = false;
  }
};

const fetchProductImages = async (productId) => {
  try {
    const result = await productApi.getProductImages(productId);
    productImages.value = result.data || [];
  } catch (error) {
    console.error('获取商品图片失败:', error);
    productImages.value = [];
  }
};

const fetchRelatedProducts = async (productId) => {
  try {
    // 此处使用模拟数据，实际项目中应该调用相关商品API
    const categoryId = product.value?.categoryId;
    if (categoryId) {
      const result = await productApi.getProductsPage({
        page: 0,
        size: 6,
        categoryId: categoryId
      });
      
      // 过滤掉当前商品
      relatedProducts.value = result.data.content
        .filter(item => item.id !== productId)
        .slice(0, 5);
    }
  } catch (error) {
    console.error('获取相关商品失败:', error);
    relatedProducts.value = [];
  }
};

const setCurrentImage = (imageUrl) => {
  currentImage.value = imageUrl;
};

const addToCart = () => {
  if (!product.value?.isPublished) {
    ElMessage.warning('该商品已下架，无法加入购物车');
    return;
  }
  
  // 这里应该调用添加到购物车的API
  ElMessage.success(`已将 ${quantity.value} 件 ${product.value.name} 添加到购物车`);
};

const buyNow = async () => {
  if (!product.value?.isPublished) {
    ElMessage.warning('该商品已下架，无法购买');
    return;
  }
  
  // 获取用户信息
  const userStore = useUserStore();
  if (!userStore.isLoggedIn) {
    ElMessage.warning('请先登录');
    router.push('/login?redirect=' + encodeURIComponent(route.fullPath));
    return;
  }
  
  // 直接跳转到订单确认页面，将商品信息作为参数传递
  router.push({
    path: '/user/order/confirm',
    query: { 
      productId: product.value.id,
      quantity: quantity.value
    }
  });
};

const addToFavorite = () => {
  // 这里应该调用添加到收藏的API
  ElMessage.success(`已将 ${product.value.name} 添加到收藏`);
};

const viewProductDetail = (productId) => {
  router.push(`/user/product/${productId}`);
};

const goBack = () => {
  router.back();
};

// 生命周期钩子
onMounted(() => {
  const productId = route.params.id;
  if (productId) {
    fetchProductDetail(productId);
  } else {
    loading.value = false;
    product.value = null;
  }
});

// 监听路由参数变化
watch(() => route.params.id, (newId) => {
  if (newId) {
    fetchProductDetail(newId);
  }
});
</script>

<style scoped>
.product-detail-container {
  max-width: 1400px;
  margin: 0 auto;
  padding: 20px;
  width: 100%;
}

@media (max-width: 1440px) {
  .product-detail-container {
    max-width: 100%;
  }
}

.loading-placeholder,
.error-placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  min-height: 400px;
  text-align: center;
}

.spinner {
  border: 4px solid rgba(0, 0, 0, 0.1);
  border-left-color: #409EFF;
  border-radius: 50%;
  width: 40px;
  height: 40px;
  animation: spin 1s linear infinite;
  margin-bottom: 20px;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.product-detail-content {
  display: flex;
  gap: 40px;
  margin-bottom: 40px;
}

.product-gallery {
  flex: 1;
  max-width: 500px;
}

.main-image {
  position: relative;
  border: 1px solid #eee;
  border-radius: 8px;
  overflow: hidden;
  margin-bottom: 20px;
  height: 400px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #f8f8f8;
}

.product-badges {
  position: absolute;
  top: 10px;
  left: 10px;
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.badge {
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: bold;
  color: white;
  text-transform: uppercase;
}

.badge.new {
  background-color: #409EFF;
}

.badge.hot {
  background-color: #F56C6C;
}

.badge.recommend {
  background-color: #E6A23C;
}

.thumbnail-list {
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
}

.thumbnail {
  width: 80px;
  height: 80px;
  border: 1px solid #ddd;
  border-radius: 4px;
  overflow: hidden;
  cursor: pointer;
  transition: transform 0.2s, border-color 0.2s;
}

.thumbnail:hover {
  border-color: #409EFF;
}

.thumbnail.active {
  border-color: #409EFF;
  transform: scale(1.05);
}

.thumbnail img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.product-info {
  flex: 1;
}

.product-title {
  font-size: 24px;
  font-weight: 600;
  margin: 0 0 20px;
  color: #333;
  line-height: 1.3;
}

.product-meta {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
  margin-bottom: 20px;
  color: #666;
}

.meta-item {
  display: flex;
}

.label {
  color: #999;
  margin-right: 5px;
}

.product-price {
  display: flex;
  align-items: center;
  margin-bottom: 30px;
}

.current-price {
  font-size: 28px;
  font-weight: 600;
  color: #F56C6C;
  margin-right: 10px;
}

.original-price {
  font-size: 16px;
  color: #999;
  text-decoration: line-through;
  margin-right: 10px;
}

.discount-tag {
  background-color: #F56C6C;
  color: white;
  padding: 3px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: bold;
}

.product-actions {
  margin-bottom: 30px;
}

.quantity-selector {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.quantity-selector .label {
  margin-right: 10px;
}

.stock-info {
  margin-left: 15px;
  color: #666;
  font-size: 14px;
}

.action-buttons {
  display: flex;
  gap: 10px;
  margin-bottom: 15px;
}

.product-status {
  margin-top: 15px;
}

.product-attributes {
  margin-top: 30px;
  border-top: 1px solid #eee;
  padding-top: 20px;
}

.attribute-title {
  font-size: 16px;
  font-weight: 600;
  color: #333;
  margin-bottom: 10px;
}

.attribute-list {
  list-style: none;
  padding: 0;
  margin: 0;
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
  gap: 10px;
}

.attribute-item {
  padding: 8px 0;
  display: flex;
}

.attribute-name {
  color: #666;
  margin-right: 5px;
}

.attribute-value {
  color: #333;
}

.product-description-section {
  margin-bottom: 40px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  padding: 20px;
}

.product-description {
  padding: 20px 0;
  color: #666;
  line-height: 1.6;
}

.related-products-section {
  margin-bottom: 40px;
}

.section-title {
  font-size: 20px;
  font-weight: 600;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
  color: #333;
}

.products-slider {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 20px;
}

.product-card {
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  transition: transform 0.3s, box-shadow 0.3s;
  cursor: pointer;
  background-color: #fff;
}

.product-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.2);
}

.product-image {
  height: 200px;
  overflow: hidden;
}

.product-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.5s;
}

.product-card:hover .product-image img {
  transform: scale(1.05);
}

.product-card-info {
  padding: 15px;
}

.product-card-name {
  font-size: 14px;
  margin: 0 0 10px;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
  height: 40px;
}

.product-card-price {
  font-size: 16px;
  font-weight: 600;
  color: #F56C6C;
}

@media (max-width: 768px) {
  .product-detail-content {
    flex-direction: column;
  }
  
  .product-gallery {
    max-width: 100%;
  }
  
  .action-buttons {
    flex-wrap: wrap;
  }
  
  .products-slider {
    grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
  }
}
</style> 